package aps.module_Machines;

//Java
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;

//Minecraft
import net.minecraft.src.Block;
import net.minecraft.src.Container;
import net.minecraft.src.GuiButton;
import net.minecraft.src.GuiContainer;
import net.minecraft.src.GuiScreen;
import net.minecraft.src.InventoryPlayer;
import net.minecraft.src.Item;

//Forge
import net.minecraftforge.client.MinecraftForgeClient;

//Buildcraft
import buildcraft.core.network.TileNetworkData;
import buildcraft.core.network.PacketPayload;
import buildcraft.core.proxy.CoreProxy;

//APS
import aps.GuiAPSButton;
import aps.GuiAPSSlider;
import aps.module_Core.APSPacketIDs;
import aps.module_Core.APSPacketUpdate;
import aps.module_Core.ContainerAPS;
import aps.BuildcraftAPS;
import aps.module_Machines.TileEntityEnergyDirector.UpdateMessage;
import aps.module_Machines.TileEntityEnergyDirector;


public class GuiEnergyDirector extends GuiContainer
{
	private TileEntityEnergyDirector directorInventory;
	
	int CurrentSide = 0;
	float[] minvalue_old = {-1, -1, -1, -1};
	float[] gatevalue_old = {-1, -1, -1, -1};
	int[] priority_old = {-1, -1, -1, -1};
	GuiAPSButton PrevSide;
	GuiAPSButton NextSide;
	GuiAPSButton PrioritySelector;
	GuiAPSButton ModeSelector;
	GuiAPSSlider ValueSlider;
	
	String guiFile = BuildcraftAPS.imageFilesRoot + "EnergyDirectorGUI.png";
	
	public GuiEnergyDirector(TileEntityEnergyDirector director, InventoryPlayer playerInv, int currentSide)
	{
		super(new ContainerAPS(director, playerInv));
		directorInventory = director;
		CurrentSide = currentSide;
	}
	
	public GuiEnergyDirector(TileEntityEnergyDirector director, InventoryPlayer playerInv)
	{
		super(new ContainerAPS(playerInv));
		directorInventory = director;
	}
	
	@Override
	public void initGui()
	{
		super.initGui();
		
		CurrentSide = directorInventory.lastSideViewed;
		
		int topLeftX = (width - xSize) / 2;
		int topLeftY = (height - ySize) / 2;
		
		//(int id, int xPos, int yPos, int texXPos, int texYPos, int texWidth, int texHeight, String tex, String label)
		PrevSide = new GuiAPSButton(420, topLeftX + 149, topLeftY + 21, getTextureOffsetBySideWrapped(CurrentSide - 1), 170, 16, 8, guiFile, "");
		NextSide = new GuiAPSButton(421, topLeftX + 149, topLeftY + 31, getTextureOffsetBySideWrapped(CurrentSide + 1), 170, 16, 8, guiFile, "");
		PrioritySelector = new GuiAPSButton(422, topLeftX + 12, topLeftY + 61, 176 + (directorInventory.routeMode ? 0 : 10), 8 + (10 * directorInventory.getPriority(CurrentSide)), 10, 10, guiFile, "");
		PrioritySelector.enabled = directorInventory.routeMode;
		ModeSelector = new GuiAPSButton(423, topLeftX + 24, topLeftY + 62, 18 - (directorInventory.routeMode ? 8 : 0), 178, 11, 8, guiFile, "");
		
		//(int id, int xPos, int yPos, int width, int height, int notchTexXPos, int notchTexYPos, int notchTexWidth, int notchTexHeight, String notchTex, String label, float startingValue)
		ValueSlider = new GuiAPSSlider(424, topLeftX + 38, topLeftY + 63, 80, 8, 184, 0, 5, 7, guiFile, "", 0.0F);
		if (directorInventory.routeMode)
			ValueSlider.setSliderValue(directorInventory.getScaledMinimumPowerValue(CurrentSide, 1));
		else
			ValueSlider.setSliderValue(directorInventory.getScaledGateValue(CurrentSide, 1));
		
		controlList.add(PrevSide);
		controlList.add(NextSide);
		controlList.add(PrioritySelector);
		controlList.add(ModeSelector);
		
		controlList.add(ValueSlider);
	}
	
	@Override
	protected void mouseMovedOrUp(int posX, int posY, int event)
	{
		if (event == 0)  //mouse up event
		{
			if (ValueSlider.dragging == true)
			{
				ValueSlider.dragging = false; //stop moving
				
				if (directorInventory.routeMode)
					directorInventory.setMinimumPowerValue(CurrentSide, ValueSlider.getScaledSliderValue(directorInventory.MaxPowerOut));
				else
					directorInventory.setGateValue(CurrentSide, ValueSlider.getScaledSliderValue(1));
				
				sendUpdatePacket(); //update tile entity
			}
		}
	}
	
	@Override
	protected void actionPerformed(GuiButton button)
	{
		if(!button.enabled)
        {
            return;
        }
		
		switch(button.id)
		{
			case 420:
				prevSide();
				break;
			case 421:
				nextSide();
				break;
			case 422:
				nextPriority();
				break;
			case 423:
				modeSwitch();
				break;
			case 424:
				return;
		}
		
		sendUpdatePacket();
	}
	
	protected void drawGuiContainerForegroundLayer(int x, int y)
    {
		String string = null;
		
		if (directorInventory.routeMode)
		{
			if (directorInventory.defaultRoute != CurrentSide)
				string = String.valueOf((int)ValueSlider.getScaledSliderValue(directorInventory.MaxPowerOut)); //only draw the number if this isnt a default route 
		}
		else
		{
			string = String.valueOf((int)ValueSlider.getScaledSliderValue(100)) + "%";
		}
		
		fontRenderer.drawString(string, 117 - fontRenderer.getStringWidth(string), 62, 0x404040);
    }
	
	float PowerGaugeMA = 0; int PowerGaugeMANodes = 30;
	
	protected void drawGuiContainerBackgroundLayer(float f, int i , int j)
    {
		int guiTex = mc.renderEngine.getTexture(guiFile);
        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
        int topLeftX = (width - xSize) / 2;
        int topLeftY = (height - ySize) / 2;
        mc.renderEngine.bindTexture(guiTex);
		
		drawTexturedModalRect(topLeftX, topLeftY, 0, 0, xSize, ySize);
		
		if (directorInventory.routeMode){
			if (directorInventory.defaultRoute == CurrentSide){
				drawTexturedModalRect(topLeftX + 37, topLeftY + 61, 0, 186, 82, 10);
				ValueSlider.enabled = false;
				ValueSlider.drawButton = false;
		 	}else{
		 		ValueSlider.enabled = true;
				ValueSlider.drawButton = true;
		 	}
			//directorInventory.setMinimumPowerValue(CurrentSide, ValueSlider.getScaledSliderValue(directorInventory.MaxPowerOut));
		}
		//else
			//directorInventory.setGateValue(CurrentSide, ValueSlider.getScaledSliderValue(1));
		
		
		
		directorInventory.lastSideViewed = CurrentSide;
        
        displayBorder(topLeftX + 6, topLeftY + 16, 34, 16);
        
        PowerGaugeMA -= PowerGaugeMA / PowerGaugeMANodes;
        PowerGaugeMA += directorInventory.getScaledLastPowerOutput(CurrentSide, 50);
        displayTempGauge(topLeftX, topLeftY, 127, 23, (int) (PowerGaugeMA / PowerGaugeMANodes));
        
        displayPowerGauge(topLeftX, topLeftY, 13, 35, (int) directorInventory.getScaledLastMinimumPowerOut(CurrentSide, 80));
        displayPowerGauge(topLeftX, topLeftY, 13, 56, (int) directorInventory.getScaledLastGatePowerOut(CurrentSide, 80));
        
        displayScreenOutput(topLeftX, topLeftY);
    }
	
	void nextPriority()
	{
		if (directorInventory.defaultRoute == -1){ 
			if (directorInventory.getPriority(CurrentSide) == 3)
				directorInventory.setPriority(CurrentSide, 0);
			else
				directorInventory.setPriority(CurrentSide, directorInventory.getPriority(CurrentSide) + 1);
			
		}else{
			if (directorInventory.getPriority(CurrentSide) == 3 || directorInventory.getPriority(CurrentSide) == 2){
				directorInventory.setPriority(CurrentSide, 0);
			}else{
				directorInventory.setPriority(CurrentSide, directorInventory.getPriority(CurrentSide) + 1);
			}
		}
		
		PrioritySelector.setTexYPos(8 + (10 * directorInventory.getPriority(CurrentSide)));
		
		//sendUpdatePacket();
	}
	
	void nextSide()
	{
		if(CurrentSide == 3) CurrentSide = 0;
		else CurrentSide++;
		
		if (directorInventory.routeMode)
			ValueSlider.setSliderValue(directorInventory.getScaledGateValue(CurrentSide, 1));
		else 
			ValueSlider.setSliderValue(directorInventory.getScaledMinimumPowerValue(CurrentSide, 1));

		PrioritySelector.setTexYPos(8 + (10 * directorInventory.getPriority(CurrentSide)));
		PrevSide.setTexXPos(getTextureOffsetBySideWrapped(CurrentSide - 1));
		NextSide.setTexXPos(getTextureOffsetBySideWrapped(CurrentSide + 1));
		PowerGaugeMA = directorInventory.getScaledLastPowerOutput(CurrentSide, 50 + PowerGaugeMANodes);
		
		//sendUpdatePacket();
	}
	
	void prevSide()
	{
		if(CurrentSide == 0) CurrentSide = 3;
		else CurrentSide--;
		
		if (directorInventory.routeMode)
			ValueSlider.setSliderValue(directorInventory.getScaledGateValue(CurrentSide, 1));
		else 
			ValueSlider.setSliderValue(directorInventory.getScaledMinimumPowerValue(CurrentSide, 1));
		
		PrioritySelector.setTexYPos(8 + (10 * directorInventory.getPriority(CurrentSide)));
		PrevSide.setTexXPos(getTextureOffsetBySideWrapped(CurrentSide - 1));
		NextSide.setTexXPos(getTextureOffsetBySideWrapped(CurrentSide + 1));
		PowerGaugeMA = directorInventory.getScaledLastPowerOutput(CurrentSide, 50 + PowerGaugeMANodes);
		
		//sendUpdatePacket();
	}
	
	void modeSwitch()
	{
		
		directorInventory.routeMode = !directorInventory.routeMode; //switch mode
		
		//change texture for button
		ModeSelector.setTexXPos(18 - (directorInventory.routeMode ? 8 : 0));
		
		//enable/disable priority button accordingly
		PrioritySelector.setTexXPos(176 + (directorInventory.routeMode ? 0 : 10));
		PrioritySelector.enabled = directorInventory.routeMode;
		
		if (directorInventory.routeMode)
			ValueSlider.setSliderValue(directorInventory.getScaledGateValue(CurrentSide, 1));
		else 
			ValueSlider.setSliderValue(directorInventory.getScaledMinimumPowerValue(CurrentSide, 1));
		
		//sendUpdatePacket();
	}
	
	int getTextureOffset()
	{
		if(CurrentSide < 0 || CurrentSide > 3) return 10;
		return 10 + (CurrentSide * 20);
	}
	
	int getTextureOffsetBySideWrapped(int Side)
	{
		if(Side < 0) Side += 4;
		if(Side > 3) Side -= 4;
		return 10 + (Side * 20);
	}
	
	private void displayBorder(int BorderTopLeftX, int BorderTopLeftY, int BorderWidth, int BorderHeight)
	{
		MinecraftForgeClient.preloadTexture(guiFile);
		
		for(int i = 0; i < BorderWidth; i++)
		{
			for(int j = 0; j < BorderHeight; j++)
			{
				int BorderSectionX = BorderTopLeftX + (i * 4);
				int BorderSectionY = BorderTopLeftY + (j * 4);
				if(i == 0) //Left Side
				{
					if(j == 0)
						drawTexturedModalRect(BorderSectionX, BorderSectionY, getTextureOffset() + 4, 166, 4, 4); //Top
					else if(j == BorderHeight - 1)
						drawTexturedModalRect(BorderSectionX, BorderSectionY, getTextureOffset() + 12, 166, 4, 4); //Bottom
					else
						drawTexturedModalRect(BorderSectionX, BorderSectionY, getTextureOffset(), 166, 4, 4); //Side
				}
				else if(i == BorderWidth - 1) //Right Side
				{
					if(j == 0)
						drawTexturedModalRect(BorderSectionX, BorderSectionY, getTextureOffset() + 8, 166, 4, 4); //Top
					else if(j == BorderHeight - 1)
						drawTexturedModalRect(BorderSectionX, BorderSectionY, getTextureOffset() + 16, 166, 4, 4); //Bottom
					else
						drawTexturedModalRect(BorderSectionX, BorderSectionY, getTextureOffset(), 166, 4, 4); //Side
				}
				else //Middle
				{
					if(j == 0 || j == BorderHeight - 1)
						drawTexturedModalRect(BorderSectionX, BorderSectionY, getTextureOffset(), 166, 4, 4); //Top or Bottom
				}
			}
		}
	}
	
	private void displayTempGauge(int TopLeftX, int TopLeftY, int GaugeTopLeftX, int GaugeTopLeftY, int BarHeight)
	{
		MinecraftForgeClient.preloadTexture(guiFile);
		
		int start = 0;

		while (true)
		{
			int x = 0;

			if (BarHeight > 8) {
				x = 8;
				BarHeight -= 8;
			} else {
				x = BarHeight;
				BarHeight = 0;
			}

			drawTexturedModalRect(TopLeftX + GaugeTopLeftX, TopLeftY + GaugeTopLeftY + 50 - x - start, 176, 8 - x, 8, x); //The 58 is the gauge height
			start = start + 8;

			if (x == 0 || BarHeight == 0) {
				break;
			}
		} //This while draws the repeating gauge graphic.
    }
	
	private void displayPowerGauge(int TopLeftX, int TopLeftY, int GaugeTopLeftX, int GaugeTopLeftY, int BarWidth)
	{
		MinecraftForgeClient.preloadTexture(guiFile);
		
		int start = 0;

		while (true)
		{
			int x = 0;

			if (BarWidth > 8) {
				x = 8;
				BarWidth -= 8;
			} else {
				x = BarWidth;
				BarWidth = 0;
			}

			drawTexturedModalRect(TopLeftX + GaugeTopLeftX + start, TopLeftY + GaugeTopLeftY, 176, 0, x, 8);
			start = start + 8;

			if (x == 0 || BarWidth == 0) {
				break;
			}
		} //This while draws the repeating gauge graphic.
    }
	
	public void displayScreenOutput(int posX, int posY)
	{
		for (int i = 0; i < 3; i++)
		{
			String text = directorInventory.text[i];
			
			if (text != null && !text.equals("")) //holds text
			{
				if (text.contains("[r]")) //red warning text
					fontRenderer.drawString(text.replace("[r]", ""), posX + 13, posY + 26 + (fontRenderer.FONT_HEIGHT * i) + 1, 0xEE0000);
				else if(text.contains("[b]")) //blue notice text
					fontRenderer.drawString(text.replace("[b]", ""), posX + 13, posY + 26 + (fontRenderer.FONT_HEIGHT * i) + 1, 0x0000EE);
				else  //default green text
					fontRenderer.drawString(text, posX + 13, posY + 26 + (fontRenderer.FONT_HEIGHT * i) + 1, 0x00EE00);
			}
		}
	}
	
	public void sendUpdatePacket()
	{		
		UpdateMessage message = new UpdateMessage();

		message.Side = CurrentSide;
		message.minValue = directorInventory.PowerData[1][CurrentSide];
		message.gateValue = directorInventory.getScaledGateValue(CurrentSide, 1);
		message.priority = directorInventory.getPriority(CurrentSide);
		message.mode = directorInventory.routeMode;
		
		if (CoreProxy.proxy.isRenderWorld(directorInventory.worldObj))
		{
			PacketPayload payload = TileEntityEnergyDirector.updateMessageWrapper.toPayload(directorInventory.xCoord, directorInventory.yCoord, directorInventory.zCoord, message);
			
			APSPacketUpdate packet = new APSPacketUpdate(APSPacketIDs.UPDATE_ENERGYREDIRECTOR, payload);
			packet.posX = directorInventory.xCoord;
			packet.posY = directorInventory.yCoord;
			packet.posZ = directorInventory.zCoord;
			
			CoreProxy.proxy.sendToServer(packet.getPacket());
		}
	}
}